import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['Authorization'] = `Bearer ${store.getters.token}`
  }
  return config
}, error => { return Promise.reject(error) }
)

service.interceptors.response.use(
  res => {
    const { data } = res
    if (data.code === 200) {
      return data
    } else {
      Message.error(data.message)
      return Promise.reject(new Error(data.message))
    }
  }, error => {
    if (error.status && error.status === 401) {
      store.dispatch('user/logout')
      router.push('/login')
    } else {
      Message.error(error.message)
    }
    return Promise.reject(error)
  }
)

export default service
